package com.hcb.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hcb.adapter.AdapterListSearchResponder;
import com.hcb.app911.MainActivity;
import com.hcb.app911.R;
import com.hcb.constants.Constants;
import com.hcb.dto.ResponderDTO;
import com.hcb.fragment.ListSearchResponceFragment.VerySlowTask;
import com.hcb.fragment.ListSearchResponceFragment.VerySlowTaskKeySearch;
import com.hcb.location.DistanceLocation;
import com.hcb.webservice.ServiceHandler;

public class ListSearchResponce extends Fragment implements OnClickListener, OnItemClickListener {
	ListView lvSearchResponce;
	AdapterListSearchResponder adapter;
	ArrayList<Object> arrData;
	TextView txttypesearch, txtnamesearch;
	ImageView imgheadersearch;
	DistanceLocation distanceLocation;
	Dialog dialog;
	Button btnMore;
	String keyword = "";
	AnimationDrawable frameAnimation;
	boolean flag = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(
				R.layout.fragment_list_search_reponder, container, false);
		
		((MainActivity)this.getActivity()).getImgDetail().setImageResource(R.drawable.mydetail);
		((MainActivity)this.getActivity()).getImgHome().setImageResource(R.drawable.icon);
		btnMore = (Button) rootView.findViewById(R.id.btnMore);
		btnMore.setOnClickListener(this);
		lvSearchResponce = (ListView) rootView
				.findViewById(R.id.lvSearchResponce);

		View headersearch = inflater.inflate(R.layout.header_search_reponder,
				null, false);
		lvSearchResponce.addHeaderView(headersearch);

		txttypesearch = (TextView) headersearch
				.findViewById(R.id.txttypesearch);
		txtnamesearch = (TextView) headersearch
				.findViewById(R.id.txtnamesearch);
		imgheadersearch = (ImageView) headersearch
				.findViewById(R.id.imgheadersearch);

		distanceLocation = new DistanceLocation(getActivity());
		arrData = new ArrayList<Object>();
		adapter = new AdapterListSearchResponder(getActivity(),
				R.layout.fragment_list_search_reponder, arrData);
		lvSearchResponce.setAdapter(adapter);
		lvSearchResponce.setOnItemClickListener(this);
		
		
		Bundle bundle = getArguments();
		
		keyword = bundle.getString("keyseach");
		if(!keyword.equalsIgnoreCase("")){
			txttypesearch.setText("Search Result Listing");
			txttypesearch.setTextSize(20);		
			imgheadersearch.setImageResource(R.drawable.searchkeywork);
			new VerySlowTaskKeySearch(keyword).execute();
		}
		

		
		return rootView;
	}

	Comparator<Object> objComparator = new Comparator<Object>() {
	    public int compare(Object o1, Object o2) {
	    	ResponderDTO dto = (ResponderDTO)o1;
	    	String str1 = dto.getAdded_on();
	    	String numberOnly1= str1.replaceAll("[^0-9]", "");
	    	ResponderDTO dto2 = (ResponderDTO)o2;
	    	String str2 = dto2.getAdded_on();
	    	String numberOnly2= str2.replaceAll("[^0-9]", "");
	        int no1 = Integer.parseInt(numberOnly1);
	        int no2 = Integer.parseInt(numberOnly2);
	        return  no1 < no2 ? -1 : no1 == no2 ? 0 : 1;
	    }
	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	
	
	
	public class VerySlowTaskKeySearch extends AsyncTask<Void, Void, Void> {
		String _keysearch = "";

		public VerySlowTaskKeySearch(String keysearch) {
			this._keysearch = keysearch;
			dialog = new Dialog(getActivity(), R.style.NewDialog);
			dialog.setContentView(R.layout.loading);
			
			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.GET_RESPONDER_KEYWORD));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair("keyword",
					_keysearch));

			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject json = new JSONObject(jsonStr);
					String conn = json.getString("result");
					if (conn.contains("success")) {
						JSONArray databody = json.getJSONArray("data_body");
						int n = Math.min(3, databody.length());
						if(flag){
							int m = arrData.size();
//							int lengarr = databody.length() - m;
							for (int i = m; i < databody.length(); i++) {
								JSONObject item = databody.getJSONObject(i);
								String responder_type = item
										.getString("responder_type");
//								if (_typesearch.contains(responder_type)) {
									ResponderDTO res = new ResponderDTO();

									res.setResponder_name(item
											.getString("responder_name"));
									res.setStreet(item.getString("street"));
									res.setTown(item.getString("town"));
									res.setState(item.getString("state"));
									res.setContact_number_one(item
											.getString("contact_number_one"));
									res.setAdded_on(String.valueOf((int) distanceLocation.getDistance(
											Double.parseDouble(item
													.getString("latitude")),
											Double.parseDouble(item
													.getString("longitude"))))
											+ " miles");
									
									arrData.add(res);
//								}

							}
						}else{
							for (int i = 0; i < n; i++) {
								JSONObject item = databody.getJSONObject(i);
								String responder_type = item
										.getString("responder_type");
//								if (_typesearch.contains(responder_type)) {
									ResponderDTO res = new ResponderDTO();

									res.setResponder_name(item
											.getString("responder_name"));
									res.setStreet(item.getString("street"));
									res.setTown(item.getString("town"));
									res.setState(item.getString("state"));
									res.setContact_number_one(item
											.getString("contact_number_one"));
									res.setAdded_on(String.valueOf((int) distanceLocation.getDistance(
											Double.parseDouble(item
													.getString("latitude")),
											Double.parseDouble(item
													.getString("longitude"))))
											+ " miles");
									
									arrData.add(res);
//								}

							}
						}
						

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}
		
		
		

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Collections.sort(arrData, objComparator);
			adapter.notifyDataSetChanged();
			dialog.dismiss();
			btnMore.setBackgroundResource(R.drawable.more);
		}

	}




	@Override
	public void onClick(View v) {
		btnMore.setBackgroundResource(R.drawable.moref);
		flag = true;
		new VerySlowTaskKeySearch(keyword).execute();
		
	}




	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (adapter.getArrObject().size() >= 1) {
			ResponderDTO re = null;

			try {
				re = (ResponderDTO) lvSearchResponce
						.getItemAtPosition(position);
				String numberphone = re.getContact_number_one();
				// set the data
				if (!numberphone.equalsIgnoreCase("")) {
					String uri = "tel:" + numberphone.toString();
					Intent callIntent = new Intent(Intent.ACTION_CALL,
							Uri.parse(uri));

					startActivity(callIntent);
				}
			} catch (Exception e) {

				e.printStackTrace();
			}

		}
		
	}
}

